package com.asset.action;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.asset.pojo.BranchOffice;
import com.asset.pojo.Department;
import com.asset.pojo.User;
import com.asset.utils.*;
import com.opensymphony.xwork2.util.logging.Logger;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.*;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;


public class UserAction extends BaseAction{
	private User user;
    private Long id;
    private String name;
    private String password;
    private String department;
    private Integer code;
    private Integer branchOfficeId;
    private String remark;
    private Long[] ids;
    private String userRoleKey;
    private String userStatusKey;
	private String opera; // 'add'-添加用户信息，‘modify’-修改用户信息
    private List<User> userList;
    private JSONObject tableData;

    private JSONArray departmentArr;
    private String departQueryName;
    //表格查询
    private String queryName;
    private Integer draw;
    private Integer length;
    private Integer start;

    private File file;

    //操作结果信息返回
    private String operationResult;

    private List<BranchOffice> branchOfficeList;
	public String toAddUser(){
        Long id = new Long(0);
        user = new User();
        user.setId(id);
        branchOfficeList = branchOfficeService.listBranchOffice(null);
		return SUCCESS;
	}
	public String addUser() {
	    try {
	        user = new User();
            user.setAddedTime(new Date());
            user.setName(name);
            user.setPassword(password);
            user.setDepartment(department);
            user.setStatus(User.Status.getEnum(null,userStatusKey,null).getValue());
            user.setRole(User.Role.getEnum(null,userRoleKey,null).getValue());
            user.setRemark(remark);
            user.setCode(code);
            user.setBranchOffice(branchOfficeId);
            user.setBranchOffice(branchOfficeId);
            user.setCode(code);
            userService.addUser(user);

            operationResult = "success";
        }catch (Exception e){
	        e.printStackTrace();
            operationResult = "fail";
        }
		return SUCCESS;
	}
	public String addUserBatch() {
	    try{
            InputStream fs=new FileInputStream(file);
            InputStreamReader fsr=new InputStreamReader(fs,"GBK");
            List<List<String>> lls = CsvUtil.readCSVFile(fsr);
            for(int i = 1; i<lls.size(); i++){
                User newUser = new User();
                List<String> ls = lls.get(i);
                if (ls.get(1) != null && !ls.get(1).equals("")) {
                    //公司
                    BranchOffice branchOffice = branchOfficeService.getBranchOfficeByName(ls.get(1));
                    if(branchOffice != null){
                        newUser.setBranchOffice(branchOffice.getId());
                    }
                }
                if (ls.get(2) != null && !ls.get(2).equals("")) {
                    //部门
                    newUser.setDepartment(ls.get(2));
                }
                if (ls.get(4) != null && !ls.get(4).equals("")) {
                    //地区
                    newUser.setArea(ls.get(4));
                }
                if (ls.get(5) != null && !ls.get(5).equals("")) {
                    //编号
                    newUser.setCode(Integer.parseInt(ls.get(5)));
                }
                if (ls.get(6) != null && !ls.get(6).equals("")) {
                    //姓名
                    newUser.setName(ls.get(6));
                }
                if (ls.get(7) != null && !ls.get(7).equals("")) {
                    //性别
//                    newUser.set(ls.get(7));
                }
                newUser.setPassword("123456");
                newUser.setRole(User.Role.User.getValue());
                newUser.setStatus(User.Status.Normal.getValue());
                newUser.setAddedTime(new Date());
                newUser.setModifyTime(new Date());
                userService.addUser(newUser);
            }
            System.out.println(lls);
        }catch (Exception e){

        }
	    return SUCCESS;
    }

	public String listUser(){
        return SUCCESS;
	}
	public String ajaxListUserData(){
        userList = userService.listUser(queryName,start,length);
        Integer recordsTotal = userService.listUser(queryName,null,null).size();
        tableData = new JSONObject();
        JSONArray userJsonArr = new JSONArray();
        for(User user : userList){
            JSONObject userJSON = new JSONObject();
            userJSON.put("id",user.getId());
            userJSON.put("name",user.getName());
            userJSON.put("role",User.Role.getEnum(user.getRole(),null,null).name());
            userJSON.put("status",User.Status.getEnum(user.getStatus(),null,null).name());
            userJSON.put("addedTime", new SimpleDateFormat("yyyy年MM月dd日 HH时mm分").format(user.getAddedTime()));
            userJSON.put("Office",user.getOffice().getName());
            userJsonArr.add(userJSON);
        }
        tableData.put("draw", draw);
        tableData.put("recordsTotal",recordsTotal);
        tableData.put("data", userJsonArr);
        tableData.put("recordsFiltered", recordsTotal);
        return SUCCESS;
    }
	public String toModifyUser(){
        user = userService.getUserById(id);
        userRoleKey = User.Role.getEnum(user.getRole(),null,null).name();
        userStatusKey = User.Status.getEnum(user.getStatus(),null,null).name();
        branchOfficeList = branchOfficeService.listBranchOffice(null);
        return SUCCESS;
    }

	public String modifyUser() {
        if(user == null){
            user = userService.getUserById(id);
        }
        user.setName(name);
        user.setPassword(password);
        user.setDepartment(department);
        user.setStatus(User.Status.getEnum(null,userStatusKey,null).getValue());
        user.setRole(User.Role.getEnum(null,userRoleKey,null).getValue());
        user.setModifyTime(new Date());
        user.setRemark(remark);
        user.setBranchOffice(branchOfficeId);
        user.setCode(code);
        userService.modifyUser(user);
        operationResult = "success";
        return SUCCESS;
	}
    public String deleteUserBatch(){
        if(ArrayUtils.isNotEmpty(ids)){
            for(Long idd : ids){
                user = userService.getUserById(idd);
                user.setModifyTime(new Date());
                user.setStatus(User.Status.Deleted.getValue());
                userService.modifyUser(user);
            }
            operationResult = "success";
            return SUCCESS;
        }else{
            operationResult = "fail";
            return SUCCESS;
        }
    }

    public String exportUserExcel(){
        List<User> assetList=userService.listUser(null,null,null);
        String excelName="信息表";
        try {
            Workbook wb=getUserExcel(assetList,excelName);
            OutputStream out = getResponse().getOutputStream();
            wb.write(out);
            out.flush();
            out.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            getSession().setAttribute("tip", "导出Excel失败");
        }
        return null;
    }

    private Workbook getUserExcel(List<User> userList, String excelName) throws Exception{
        List<String> listTitle = new ArrayList<String>();
        listTitle.add("用户名");
        listTitle.add("角色");
        listTitle.add("添加时间");
        listTitle.add("状态");
        Object[] oarr = listTitle.toArray();
        //HttpServletResponse response = ServletActionContext.getResponse();
        getResponse().setContentType("application/vnd.ms-excel;charset=UTF-8");
        if(getRequest().getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0)// firefox浏览器
            excelName = new String(excelName.getBytes("UTF-8"), "ISO8859-1");
        else if(getRequest().getHeader("User-Agent").toLowerCase().indexOf("trident") > 0)// IE浏览器，ie11后请求头中的User-Agent中不再有"MSIE"
            excelName = URLEncoder.encode(excelName, "UTF-8");
        else if(getRequest().getHeader("User-Agent").toLowerCase().indexOf("chrome") > 0)// google浏览器
            excelName = new String(excelName.getBytes("UTF-8"), "ISO8859-1");
        // 转码防止乱码
        getResponse().addHeader("Content-Disposition", "attachment;filename=" + excelName + ".xls");
        List<POIExcelBaseBean> listRows = new ArrayList<POIExcelBaseBean>();
        SimpleDateFormat fd0 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat fd1 = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
        for(User a: userList){
            String name = "";
            String role = "";
            String addedTime = "";
            String status = "";
            if(a.getName() != null){
                name = a.getName();
            }
            if(a.getRole() != null){
                role = User.Role.getEnum(a.getRole(),null,null).getZhName();
            }
            if(a.getAddedTime() != null){
                addedTime = fd1.format(a.getAddedTime());
            }
            if(a.getStatus() != null){
                status = User.Status.getEnum(a.getRole(),null,null).getZhName();
            }

            listRows.add(new POIExcelUserBean(name, role, addedTime,status));
        }
        return POIExcelUtils.OutputExcel(oarr, listRows, 1, null, null);
    }

    public String listDepartmentArr1(){
        List<Department> departmentList = departService.listDepart(departQueryName);
        departmentArr = new JSONArray();
        for(Department department : departmentList){
            if(departQueryName == null){
                if(department.getName().contains("_")==false){
                    departmentArr.add(department);
                }
            }else{
                String parent_ [] = departQueryName.split("_");
                String chird_ [] = department.getName().split("_");
                if(parent_.length == chird_.length-1){
                    departmentArr.add(department);
                }
            }
        }
        return SUCCESS;
    }
//    getDepartTree
    public String listDepartmentArr(){
        List<Department> departmentList = departService.listDepart(null);
        departmentArr = new JSONArray();
        for(int i=4;i>=2;i--){
            Map<String,String> releationShip=getDepartmentBy(i,departmentList,departmentArr);
            departmentArr = createNode(releationShip,departmentArr);
        }
        for(Department department :departmentList){
            List<Department> departmentSingleList = departService.listDepart(department.getName());
            if(departmentSingleList.size()==1&&!departmentSingleList.get(0).getName().contains("_")){
//                if(!department.getName().contains("_")){
                JSONObject departmentJson = new JSONObject();
                departmentJson.put("name",department.getName());
                departmentArr.add(departmentJson);
            }
        }
        return SUCCESS;
    }

//    private JSONArray getChildrenNode(int level,List<Department> departments,JSONArray childNode){
//
//    }

    //依据层次结构获取，得到父级目录以及子目录的对应关系，产生 key和value的键值对,并且找到孩子节点
    private Map<String,String> getDepartmentBy(int level,List<Department> departments,JSONArray childNode){
        Map<String,String> fiterDepartments = new HashMap<String,String>();
        for(Department department : departments){
            String [] ss = department.getName().split("_");
            if(ss.length >= level){
                boolean flag = false;
                //1.孩子节点和上级节点的关系
                fiterDepartments.put(ss[level-1],ss[level-2]);
                for(Object obj : childNode){
                    //如果已经构建的树是上一级的子节点，则把子节点和父节点的关系联系起来
                    JSONObject node = (JSONObject) obj;
                    if(node.getString("name").equals(ss[level-1])){
//                        JSONObject parentNode = new JSONObject();
//                        parentNode.put("name",ss[level-1]);
//                        parentNode.put("children",);
                        flag = true;
                    }
                }
                //2.如果上一级的节点中不存在，该节点，则在孩子节点中新增节点
                if(flag==false){
                    JSONObject cObj = new JSONObject();
                    cObj.put("name",ss[level-1]);
                    childNode.add(cObj);
                }
            }
        }
        return fiterDepartments;
    }

    private JSONArray createNode(Map<String,String> filiation,JSONArray children){
        JSONArray nodes = new JSONArray();
        Set<String> parentString = new HashSet<String>();
        //获取父节点
        for(String fv:filiation.values()){
            parentString.add(fv);
        }
        //将父节点和子节点进行对应
        for(String p:parentString){
            JSONObject parentNode = new JSONObject();
            parentNode.put("name",p);
            JSONArray child = new JSONArray();
            Set set=filiation.entrySet();
            Iterator it=set.iterator();
            while (it.hasNext()){
                Map.Entry entry=(Map.Entry)it.next();
                if(entry.getValue().equals(p)) {
                    // 将子节点装入的父节点下
                    for(Object c :children){
                        JSONObject cObj = (JSONObject)c;
                        String name = cObj.getString("name");
                        if(entry.getKey().equals(name)){
                            child.add(c);
                        }
                    }
                    //装入子节点
                    if(child.size()>0){
                        parentNode.put("children",child);
                    }
                }
            }
            nodes.add(parentNode);
        }
        return nodes;
    }





    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public void setIds(Long[] ids) {
        this.ids = ids;
    }

    public String getOpera() {
        return opera;
    }

    public void setOpera(String opera) {
        this.opera = opera;
    }

    public List<User> getUserList() {
        return userList;
    }

    public void setUserList(List<User> userList) {
        this.userList = userList;
    }

    public JSONObject getTableData() {
        return tableData;
    }

    public void setTableData(JSONObject tableData) {
        this.tableData = tableData;
    }

    public String getQueryName() {
        return queryName;
    }

    public void setQueryName(String queryName) {
        this.queryName = queryName;
    }

    public Integer getDraw() {
        return draw;
    }

    public void setDraw(Integer draw) {
        this.draw = draw;
    }

    public Integer getLength() {
        return length;
    }

    public void setLength(Integer length) {
        this.length = length;
    }

    public String getUserStatusKey() {
        return userStatusKey;
    }

    public void setUserStatusKey(String userStatusKey) {
        this.userStatusKey = userStatusKey;
    }

    public String getUserRoleKey() {
        return userRoleKey;
    }

    public void setUserRoleKey(String userRoleKey) {
        this.userRoleKey = userRoleKey;
    }

    public String getOperationResult() {
        return operationResult;
    }

    public void setOperationResult(String operationResult) {
        this.operationResult = operationResult;
    }

    public Long[] getIds() {
        return ids;
    }

    public Integer getStart() {
        return start;
    }

    public void setStart(Integer start) {
        this.start = start;
    }

    public JSONArray getDepartmentArr() {
        return departmentArr;
    }

    public void setDepartmentArr(JSONArray departmentArr) {
        this.departmentArr = departmentArr;
    }

    public String getDepartQueryName() {
        return departQueryName;
    }

    public void setDepartQueryName(String departQueryName) {
        this.departQueryName = departQueryName;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public Integer getBranchOfficeId() {
        return branchOfficeId;
    }

    public void setBranchOfficeId(Integer branchOfficeId) {
        this.branchOfficeId = branchOfficeId;
    }

    public List<BranchOffice> getBranchOfficeList() {
        return branchOfficeList;
    }

    public void setBranchOfficeList(List<BranchOffice> branchOfficeList) {
        this.branchOfficeList = branchOfficeList;
    }

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }
}
